<template>
  <div>
    <sec-table
      :data="detailList"
      size="mini"
      style="width: 100%; padding: 0 0 10px 10px"
      stripe
      border
      outborder
    >
      <sec-table-column
        prop="index"
        label="序号"
        align="center"
        width="80"
      ></sec-table-column>
      <sec-table-column prop="label" label="字典标签" align="center">
        <template slot-scope="scope">
          <sec-input
            v-if="editableDetailData.editRow === scope.row"
            v-model="editableDetailData.editRow.label"
          >
            <i slot="prefix" style="color: red; font-size: 14px">*</i>
          </sec-input>
          <template v-else>{{ scope.row.label }}</template>
        </template>
      </sec-table-column>
      <sec-table-column prop="value" label="字典键值" align="center">
        <template slot-scope="scope">
          <sec-input
            v-if="editableDetailData.editRow === scope.row"
            v-model="editableDetailData.editRow.value"
          >
            <i slot="prefix" style="color: red; font-size: 14px">*</i>
          </sec-input>
          <template v-else>{{ scope.row.value }}</template>
        </template>
      </sec-table-column>
      <sec-table-column prop="sortOrder" label="字典排序" align="center">
        <template slot-scope="scope">
          <sec-input
            v-if="editableDetailData.editRow === scope.row"
            v-model="editableDetailData.editRow.sortOrder"
          >
            <i slot="prefix" style="color: red; font-size: 14px">*</i>
          </sec-input>
          <template v-else>{{ scope.row.sortOrder }}</template>
        </template>
      </sec-table-column>
      <sec-table-column prop="description" label="字典描述" align="center">
        <template slot-scope="scope">
          <sec-input
            v-if="editableDetailData.editRow === scope.row"
            v-model="editableDetailData.editRow.description"
          ></sec-input>
          <template v-else>{{ scope.row.description }}</template>
        </template>
      </sec-table-column>
      <sec-table-column align="center" fixed="right">
        <template #header>
          <sec-button type="primary" size="small" @click="handleDetailAdd"
            >新增</sec-button
          >
        </template>
        <template slot-scope="scope">
          <template v-if="editableDetailData.editRow === scope.row">
            <sec-button
              type="text"
              size="small"
              icon="sec-icon-bianji"
              @click="handleDetailSave(scope.$index, scope.row)"
              >保存</sec-button
            >
            <sec-button
              type="text"
              size="small"
              icon="sec-icon-bianji"
              @click="handleDetailCancel(scope.$index, scope.row)"
              >取消</sec-button
            >
          </template>
          <template v-else>
            <sec-button
              type="text"
              size="small"
              icon="sec-icon-bianji"
              @click="handleDetailEdit(scope.$index, scope.row)"
              >编辑</sec-button
            >
            <sec-button
              type="text"
              size="small"
              icon="sec-icon-bianji"
              @click="handleDetailDelete(scope.$index, scope.row)"
              >删除</sec-button
            >
          </template>
        </template>
      </sec-table-column>
    </sec-table>
    <div class="pagination">
      <sec-pagination
        :current-page.sync="pagination.pageNo"
        :page-size="pagination.pageSize"
        layout="total,prev, pager, next,sizes"
        :total="pagination.totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></sec-pagination>
    </div>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
import http from '@/utils/http'
export default {
  props: {
    type: {
      type: String,
      required: true
    },
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      editableDetailData: {
        editRow: null,
        isEdit: false,
        isAdd: false
      },
      emptyDetail: {},
      oldDetail: {},
      detailList: [],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalCount: 0
      },
      requiredKeys: ['label', 'value', 'sortOrder']
    }
  },
  methods: {
    msg(message, type) {
      this.$message({ message, type })
    },
    validate(obj) {
      let flag = true
      this.requiredKeys.forEach((key) => {
        if (
          obj[key] === undefined ||
          (typeof obj[key] === 'string' && obj[key].trim() === '')
        ) {
          flag = false
          return
        }
      })
      return flag
    },
    async getList(params) {
      params = { ...params, type: this.type }
      try {
        const { data } = await http.getDictItemList(params)
        this.detailList = data.rows || []
        this.pagination = {
          ...this.pagination,
          pageNo: params.pageNo,
          pageSize: data.pageSize,
          totalCount: data.totalRows
        }
        this.detailList.forEach((item, index) => {
          item.index =
            this.pagination.pageSize * (this.pagination.pageNo - 1) + index + 1
        })
      } catch (e) {
        console.error(e)
      }
    },
    // 字典详情表格编辑
    handleDetailAdd() {
      if (this.editableDetailData.isEdit || this.editableDetailData.isAdd) {
        this.msg('尚有未保存的数据！', 'warning')
        return
      }
      const newRow = cloneDeep(this.emptyDetail)
      this.detailList.push(newRow)
      this.editableDetailData.editRow = newRow
      this.editableDetailData.isAdd = true
    },
    handleDetailEdit(index, row) {
      if (this.editableDetailData.isEdit || this.editableDetailData.isAdd) {
        this.msg('尚有未保存的数据！', 'warning')
        return
      }
      this.oldDetail = cloneDeep(row)
      this.editableDetailData.editRow = row
      this.editableDetailData.isEdit = true
    },
    async handleDetailSave(index, row) {
      if (!this.validate(this.editableDetailData.editRow)) {
        this.msg('有必填项未填！', 'warning')
        return
      }
      const params = {
        ...this.editableDetailData.editRow,
        type: this.type,
        dictId: this.id
      }
      if (this.editableDetailData.isEdit) {
        try {
          const { code, message } = await http.editDictItem(params)
          if (code === '200') {
            this.msg('编辑成功！', 'success')
          } else {
            this.msg(message, 'warning')
            return
          }
        } catch (e) {
          console.error(e)
          return
        }
        this.editableDetailData.isEdit = false
      } else if (this.editableDetailData.isAdd) {
        try {
          const { code, message } = await http.addDictItem(params)
          if (code === '200') {
            this.msg('添加成功！', 'success')
          } else {
            this.msg(message, 'warning')
            return
          }
        } catch (e) {
          console.error(e)
          return
        }
        this.editableDetailData.isAdd = false
      }
      this.editableDetailData.editRow = null
      this.updateList()
    },
    handleDetailCancel(index, row) {
      this.editableDetailData.editRow = null
      if (this.editableDetailData.isAdd) {
        this.detailList.pop()
        this.editableDetailData.isAdd = false
      } else if (this.editableDetailData.isEdit) {
        Object.keys(row).forEach((key) => {
          row[key] = this.oldDetail[key]
        })
        this.oldDetail = {}
        this.editableDetailData.isEdit = false
      }
    },
    async handleDetailDelete(index, row) {
      if (this.editableDetailData.isEdit || this.editableDetailData.isAdd) {
        this.msg('尚有未保存的数据！', 'warning')
        return
      }
      this.$confirm('<div>确认删除所选字典标签吗?</div>', '提示', {
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(async () => {
        try {
          const { code } = await http.deleteDictItem({ id: row.id })
          if (code === '200') {
            this.msg('标签删除成功！', 'success')
            this.updateList()
          } else {
            this.msg('标签删除失败！', 'warning')
          }
        } catch (e) {
          console.error(e)
        }
      })
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.updateList()
    },
    handleCurrentChange(val) {
      this.pagination.pageNo = val
      this.updateList()
    },
    updateList() {
      const { totalCount, pageNo, pageSize } = this.pagination
      if (totalCount > 0 && pageNo > Math.ceil(totalCount / pageSize)) {
        return
      }

      this.getList({
        pageNo,
        pageSize
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.pagination {
  text-align: right;
}
</style>
